/**
 * <b>项目名：</b>meizuapi<br/>
 * <b>包名：</b>com.meizu.api.meizuapi<br/>
 * <b>文件名：</b>Monitor.java<br/>
 * <b>版本信息：</b> @version 1.0.0<br/>
 * <b>日期：</b>2013-5-4-下午3:14:47<br/>
 * <b>Copyright (c)</b> 2013魅族公司-版权所有<br/>
 *
 */

package org.apitool.main;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * <b>类名称：</b>Monitor<br/>
 * <b>类描述：</b>
 * 
 * <pre>
 </pre>
 * 
 * <br/>
 * <b>创建人：</b>张军强<br/>
 * <b>修改人：</b>张军强<br/>
 * <b>修改时间：</b>2013-5-4 下午3:14:47<br/>
 * <b>修改备注：</b><br/>
 * 
 * @version 1.0.0<br/>
 */

public class MonitorManager {

	private static Scheduler scheduler;

	private static HashMap<String, Map<String, JobDetail>> montorMap = new HashMap<String, Map<String, JobDetail>>();

	private static MonitorManager instance;

	public static MonitorManager getInstance() {
		if (instance == null) {
			instance = new MonitorManager();
		}
		if (scheduler == null) {
			try {
				scheduler = new StdSchedulerFactory().getScheduler();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return instance;
	}

	private MonitorManager() {

	}

	public static String addJob(String jobDesc, String host, String email) {

		StringBuffer buffer = new StringBuffer();

		try {

			Map apis = JSONObject.parseObject(jobDesc, Map.class);
			Iterator it = apis.keySet().iterator();

			Map<String, JobDetail> tmpMap = montorMap.get(host);
			if (tmpMap != null) {
				Iterator<JobDetail> tit = tmpMap.values().iterator();
				while (tit.hasNext()) {
					scheduler.deleteJob(tit.next().getKey());
				}
				tmpMap.clear();
			}

			while (it.hasNext()) {
				List<Map> arrayApi = JSONObject.parseArray(apis.get(it.next()).toString(), Map.class);
				for (int i = 0; arrayApi != null && i < arrayApi.size(); i++) {
					Map monitor = JSONObject.parseObject(arrayApi.get(i).get("monitor") == null ? "{}" : arrayApi.get(i).get("monitor").toString(), Map.class);
					if (Boolean.parseBoolean(monitor.get("isMonitor") == null ? "false" : monitor.get("isMonitor").toString())) {

						Map requestMap = JSONObject.parseObject(arrayApi.get(i).get("request").toString(), Map.class);
						Map paramMap = JSONObject.parseObject(requestMap.get("param").toString(), Map.class);
						// api.getBase().post(host +
						// requestMap.get("url").toString(), paramMap);
						JobDetail job = JobBuilder.newJob(Monitor.class).withIdentity(requestMap.get("url").toString(), host).build();
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("url", requestMap.get("url").toString());
						map.put("param", requestMap.get("param").toString());
						map.put("host", host);
						map.put("email", email);
						map.put("monitor", arrayApi.get(i).get("monitor").toString());
						map.put("assert", arrayApi.get(i).get("assert").toString());
						job.getJobDataMap().put("api", map);
						if (tmpMap != null) {
							tmpMap.put(job.getKey().toString(), job);
						} else {
							tmpMap = new HashMap<String, JobDetail>();
							tmpMap.put(job.getKey().toString(), job);
						}
						buffer.append(host + requestMap.get("url").toString() + "\n");
						CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(requestMap.get("url").toString(), host).withSchedule(CronScheduleBuilder.cronSchedule("0/4 * * * * ?")).build();
						try {

							scheduler.scheduleJob(job, trigger);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				}
			}
			montorMap.put(host, tmpMap);
			scheduler.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	/**
	 * <b>创建人：</b>张军强<br/>
	 * delJob<br/>
	 * <b>方法描述：</b> <br/>
	 * 
	 * @param parameter
	 * @param host
	 * @param parameter2
	 *            void
	 * @exception
	 * @since 1.0.0
	 */

	public String delJob(String jobDesc, String host, String email) {
		StringBuffer buffer = new StringBuffer();
		try {

			Map apis = JSONObject.parseObject(jobDesc, Map.class);
			Iterator it = apis.keySet().iterator();

			Map<String, JobDetail> tmpMap = montorMap.get(host);
			if (tmpMap != null) {
				Iterator<JobDetail> tit = tmpMap.values().iterator();
				while (tit.hasNext()) {
					JobDetail tt = tit.next();
					HashMap<String, String> api = (HashMap<String, String>) tt.getJobDataMap().get("api");
					buffer.append(api.get("host").toString() + api.get("url").toString() + "\n");
					buffer.append(tt.getKey() + "\n");
					scheduler.deleteJob(tt.getKey());
				}
				tmpMap.clear();
			}
			scheduler.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}
}
